import 'dart:math';

// import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:historyToday/config/api.dart';
import 'package:historyToday/page/detail.dart';

import 'aboutPage.dart';

class MasterPage extends StatefulWidget {
  MasterPage({Key key}) : super(key: key);

  @override
  _MasterPageState createState() => _MasterPageState();
}

class _MasterPageState extends State<MasterPage> {
  DateTime _nowDate = DateTime.now(); //当前日期
  TimeOfDay _nowTime = TimeOfDay.now(); //当前时间

  String selectDate = '';
  String selectMouth = '';
  String selectDay = '';
  String selectStr = '';

  Map resultData = {'title': null};

  // 初始化日历组件
  @override
  void initState() {
    setState(() {
      selectMouth = _nowDate.toString().split('-')[1];
      selectDay = _nowDate.toString().split('-')[2].toString().split(' ')[0];
    });
    EasyLoading.show(status: '加载中...');
    getList(selectMouth, selectDay).then((res) {
      EasyLoading.dismiss();
      setState(() {
        resultData = res;
      });
    });

    super.initState();
  }

  _showDatePicker() async {
    var result = await showDatePicker(
        context: context,
        initialDate: _nowDate, //选中的日期
        firstDate: DateTime(1900), //日期选择器上可选择的最早日期
        lastDate: DateTime(2100), //日期选择器上可选择的最晚日期
        locale: Locale("zh") //中文显示
        );
    setState(() {
      selectDate = result.toString();
      selectMouth = result.toString().split('-')[1];
      selectDay = result.toString().split('-')[2].toString().split(' ')[0];
    });
    getList(selectMouth, selectDay).then((res) {
      setState(() {
        resultData = res;
      });
    });
  }

  int m = 0;
  int d = 0;
  // 随机进入某天
  random() {
    resultData['title'] = null;
    var rng = new Random(); //随机数生成类
    setState(() {
      m = rng.nextInt(11);
      d = rng.nextInt(28);
    });
    if (m <= 9 && m > 0) {
      setState(() {
        selectMouth = '0' + m.toString();
      });
    } else if (m > 9) {
      setState(() {
        selectMouth = m.toString();
      });
    }

    if (d <= 9 && d > 0) {
      setState(() {
        selectDay = '0' + d.toString();
      });
    } else if (d > 9) {
      setState(() {
        selectDay = d.toString();
      });
    }

    getList(selectMouth, selectDay).then((res) {
      setState(() {
        resultData = res;
      });
    });
  }

  List<Widget> renderList(renderList) {
    List<Widget> list = [];
    List.generate(renderList.length, (index) {
      list.add(
        InkWell(
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => DetailPage(
                      mounth: selectMouth, day: selectDay, index: index),
                ),
              );
            },
            child: Container(
              // decoration: BoxDecoration(color: Colors.red),
              padding: EdgeInsets.all(8),
              width: MediaQuery.of(context).size.width / 2,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Container(
                      child: ClipRRect(
                    borderRadius: BorderRadius.all(Radius.circular(5)),
                    child: FadeInImage.assetNetwork(
                      placeholder: 'assets/images/placeholder.jpeg',
                      fadeInDuration: const Duration(milliseconds: 500),
                      image: renderList[index]['imgUrl'],
                    ),
                  )),
                  SizedBox(height: 5),
                  Text(
                    renderList[index]['title'],
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      color: Colors.black,
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  SizedBox(height: 5),
                  Text(
                    renderList[index]['sub'],
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      fontSize: 12,
                    ),
                  ),
                ],
              ),
            )),
      );
    });
    return list;
  }

  @override
  Widget build(BuildContext context) {
    return resultData['title'] == null
        ? Container(
            color: Colors.white,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CircularProgressIndicator(),
                SizedBox(height: 20),
                Text(
                  "正在加载",
                  style: TextStyle(color: Colors.redAccent[700], fontSize: 14),
                )
              ],
            ),
          )
        : Scaffold(
            appBar: AppBar(
                title: Text('历史上的今天'),
                backgroundColor: Colors.redAccent[700],
                actions: <Widget>[
                  IconButton(
                      icon: Icon(Icons.calendar_today),
                      tooltip: 'Add Alarm',
                      onPressed: () {
                        _showDatePicker();
                      })
                ]),
            drawer: new Drawer(
                child: new Container(
              color: const Color(0xfff1f2f3),
              child: new Column(
                children: <Widget>[
                  Container(
                    height: 75,
                    color: Colors.redAccent[700],
                  ),
                  new Container(
                    padding: new EdgeInsets.all(20.0),
                    decoration: new BoxDecoration(
                        border: Border(
                            bottom: BorderSide(
                                width: 1, color: Color(0xffe5e5e5)))),
                    child: InkWell(
                        onTap: () {
                          Navigator.pop(context);
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => AboutPage(),
                            ),
                          );
                        },
                        child: new Row(
                          children: <Widget>[
                            new Icon(Icons.exit_to_app, color: Colors.black87),
                            SizedBox(
                              width: 10,
                            ),
                            new Text('关于'),
                          ],
                        )),
                  ),
                  new Container(
                    padding: new EdgeInsets.all(20.0),
                    decoration: new BoxDecoration(
                        border: Border(
                            bottom: BorderSide(
                                width: 1, color: Color(0xffe5e5e5)))),
                    child: InkWell(
                        onTap: () {
                          Navigator.pop(context);
                          random();
                        },
                        child: new Row(
                          children: <Widget>[
                            new Icon(Icons.event_available,
                                color: Colors.black87),
                            SizedBox(
                              width: 10,
                            ),
                            new Text('随机进入一天'),
                          ],
                        )),
                  )
                ],
              ),
            )),
            body: SingleChildScrollView(
              child: Container(
                padding: EdgeInsets.only(top: 20),
                child: Wrap(
                  children: [
                    Center(
                      child: Text(resultData['title'],
                          style: TextStyle(
                            color: Colors.black,
                            fontSize: 20,
                            fontWeight: FontWeight.w600,
                          )),
                    ),
                    ...renderList(resultData['body'])
                  ],
                ),
              ),
            ));
  }
}
